#!/usr/bin/python3
import sys
import email.mime.multipart
import email.mime.text
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from email.mime.application import MIMEApplication
import smtplib

#接受：收件人，主题，内容
#返回：邮件发送结果

def send(address,content):

    title =  str(content) #邮件标题
    FROM_MAIL = "carvertime@163.com"  # 发件人
    TO_MAIL = address          # 收件人

    SMTP_SERVER = 'smtp.163.com'    #邮箱服务器
    SSL_PORT = '465'          #加密端口
    USER_NAME = FROM_MAIL     #qq邮箱用户名
    USER_PWD = "gaowenjie112"    #qq邮箱授权码
    msg = email.mime.multipart.MIMEMultipart("related")     #实例化email对象
    msg['from'] = FROM_MAIL           # 对应发件人邮箱昵称、发件人邮箱账号
    msg['to'] = TO_MAIL     # 对应收件人邮箱昵称、收件人邮箱账号
    msg['subject'] = title       # 邮件的主题

    html = f"""\
        <html>
            <h3>Hi: </h3>
            <h3>{str(content)}</h3>
            <h3>http://1.117.108.166/data.xls</h3>
            <body>
            </body>
        </html>
    """
    part = MIMEText(html, 'html','utf-8')
    msg.attach(part)

    filename = "data.xlsx"
    attachment = open("./public/data.xlsx", "rb")
    
    # instance of MIMEBase and named as p
    p = MIMEBase('application', 'octet-stream')
    
    # To change the payload into encoded form
    p.set_payload((attachment).read())
    
    # encode into base64
    encoders.encode_base64(p)
    
    p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
    
    # attach the instance 'p' to instance 'msg'
    msg.attach(p)

    try:
        # 纯粹的ssl加密方式
        smtp = smtplib.SMTP_SSL(SMTP_SERVER, SSL_PORT)   #邮件服务器地址和端口
        smtp.ehlo()  # 用户认证
        smtp.login(USER_NAME, USER_PWD)  # 括号中对应的是发件人邮箱账号、邮箱密码
        maills = [TO_MAIL]
        if TO_MAIL.find(",") == 0:
            maills = TO_MAIL.split(',')
        smtp.sendmail(FROM_MAIL, maills, msg.as_string())  # 收件人邮箱账号、发送邮件
        smtp.quit()  # 等同 smtp.close()  ,关闭连接
        print('send successfully !!!')
    except Exception as e:
        ret = False
        print(">>>>>>>:" + e)

args = sys.argv
send(args[1],args[2])